<template>
  <div class="app-container">
    <dk-query
      ref="nxIB"
      :searchForm="queryParams"
      :inputList="inputList"
      :queryTable="click().handleQuery"
      labelWidth="110"
    >
    </dk-query>

    <dk-table
      ref="table"
      :column="column"
      :pagination="paginationObjs"
      :tableData="tableData"
      :height="tableHeight"
    >
      <template #goodsName="{ scope }">
        <div>
          {{ scope.goodsName }}
          <p
            v-if="scope.inventoryAlert >= scope.inventory"
            style="
              color: red;
              position: absolute;
              bottom: -10px;
              font-size: 10px;
            "
          >
            库存预警
          </p>
        </div>
      </template>
    </dk-table>
  </div>
</template>

<script>
// 接口api：first step
import {
  getGoodsBaseList,
  delGoodsBaseType,
  editGoodsBaseType,
  editGoodsGroundingType
} from '@/api/list/shop-list.js';
import { getGoodsTypeList } from '@/api/class/commodity-class.js';

export default {
  data() {
    return {
      // 都按默认1传

      type: 1,
      loading: true,
      // 规程toolbar：two step
      inputList: [
        {
          type: 'input',
          placeholder: '请输入',
          label: '商品名称',
          name: 'goodsName',
        },
        {
          type: 'select',
          placeholder: '请选择',
          label: '商品分类',
          name: 'goodsTypeId',
          optionList: [],
        },
        {
          type: 'select',
          placeholder: '请选择',
          label: '状态',
          name: 'isGrounding',
          optionList: [
            {
              name: '上架',
              value: 1,
            },
            {
              name: '下架',
              value: 0,
            },
          ],
        },
        {
          type: 'input',
          placeholder: '请输入',
          label: '商品ID',
          name: 'id',
        },
        {
          type: 'daterange',
          placeholder: '选择创建时间',
          label: '创建时间',
          name: 'dateRange',
          fun: (row) => {
            this.queryParams.dateRange[0] = `${row[0]} 00:00:00`;
            this.queryParams.dateRange[1] = `${row[1]} 23:59:59`;
          },
        },
        {
          type: 'common-button',
          isShowAdd: true,
          hasPermissObj: {
            add: () => `${this.urlObject.permissPrefix}add`,
          },
          searchFun: (searchForm) => {
            this.queryParams = searchForm;
            this.click().handleQuery();
          },
          resetFun: () => {
            this.click().resetQuery();
          },
          addFun: () => {
            this.click().handleAdd();
          },
        },
      ],
      // 规程表头：shree step
      column: [
        {
          value: 'id',
          name: '商品ID',
        },
        {
          slot: true,
          value: 'goodsName',
          name: '商品名称',
        },
        

        {
          value: 'sort',
          name: '排序',
        },
        {
          value: 'goodsTypeName',
          name: '商品分类',
        },
        {
          value: 'coverImg',
          name: '封面图',
          type: 'image',
        },
        {
          value: 'inventory',
          name: '库存',
        },
        {
          value: 'platformPrice',
          name: '尊享价(元)',
          format: (val) => {
            return '￥' + val;
          },
        },
        {
          value: 'isSelected',
          name: '是否在首页显示',
          stateList: [
            { name: '是', value: 0 },
            { name: '否', value: 1 },
          ],
        },
        {
          value: 'isGrounding',
          name: '下架/上架',
          type: 'switch',
          fun: async (row, index) => {
            await this.interfaceObj.groundingApiName({
              id: row.id,
              isGrounding: row.isGrounding,
            });
            await this.network().getList();
          },
          valueList: [
            {
              name: '上架',
              value: 1,
            },
            {
              name: '下架',
              value: 0,
            },
          ],
        },
        {
          value: 'promotionStartTime',
          name: '活动时间',
        },
        {
          value: 'createTime',
          name: '创建时间',
        },
        {
          width: 200,
          value: 'id',
          name: '管理',
          fixed: 'right',
          type: 'button',
          fixed: 'right',
          buttonList: [
            {
              type: 'no-tooltip',
              name: '查看评价',
              fun: (row) => {
                this.click().handleComment(row);
              },
              color: 'text',
              icon: 'el-icon-edit',
              hasPermiss: () => `${this.urlObject.permissPrefix}comment`,
            },
            {
              type: 'no-tooltip',
              name: '编辑',
              fun: (row) => {
                this.click().handleUpdate(row);
              },
              color: 'text',
              icon: 'el-icon-edit',
              hasPermiss: () => `${this.urlObject.permissPrefix}edit`,
            },
            {
              type: 'no-tooltip',
              name: '删除',
              fun: (row) => {
                this.click().handleDelete(row);
              },
              color: 'text',
              icon: 'el-icon-edit',
              hasPermiss: () => `${this.urlObject.permissPrefix}del`,
            },
          ],
        },
      ],
      // 分页器
      paginationObjs: {
        paginationChange: function () {
          this.network().getList(false);
        }.bind(this),
        page: 1,
        limit: 10,
        total: 0,
        loading: false,
      },
      // 查询参数
      queryParams: {},
      // 表格数据
      tableData: [],
      // url对象：four step
      urlObject: {
        permissPrefix: 'merchant-store-manage:commodity-manage:',
        routePathPrefix: '/merchant-store-manage/commodityManage/',
      },
      // 接口存储对象：five step
      interfaceObj: {
        getApiName: getGoodsBaseList,
        editApiName: editGoodsBaseType,
        delApiName: delGoodsBaseType,
        groupApiName: getGoodsTypeList,
        groundingApiName: editGoodsGroundingType,

      },
    };
  },
  created() {
    this.network().getList();
    this.getTableHeight.call(this);
    this.network().getGroup();
  },
  methods: {
    click() {
      return {
        // 搜索
        handleQuery: async () => {
          this.paginationObjs.page = 1;
          this.network().getList();
        },
        // 重置
        resetQuery: async () => {
          this.queryParams = this.$options.data().queryParams;
          this.paginationObjs = this.$options.data().paginationObjs;
          this.network().getList();
        },
        // 详情
        handleComment: async (row) => {
          this.$router.push({
            path: `/proprietary/comment?goodsId=${row.id}`,
          });
        },
        // 新增
        handleAdd: async () => {
          this.$router.push({
            path: `${this.urlObject.routePathPrefix}edit`,
          });
        },
        // 编辑
        handleUpdate: async (row) => {
          this.$router.push({
            path: `${this.urlObject.routePathPrefix}edit/${row.id}`,
          });
        },
        // 删除
        handleDelete: async (row) => {
          this.deleteMessageBox({
            name: `商品名称：${row.name || ''}`,
            message: '是否确认删除该商品？',
          }).then(() => {
            this.network().handleDelete(row.id);
          });
        },
      };
    },
    network() {
      return {
        getList: async () => {
          const params = this.deepCopy(this.queryParams);
          delete params.dateRange;
          const obj = {
            ...params,
            // 是否促销商品，0：否，1：是
            isPromotion: 1,
            pageNum: this.paginationObjs.page,
            pageSize: this.paginationObjs.limit,
            beginTime: this.queryParams.dateRange?.[0],
            afterTime: this.queryParams.dateRange?.[1],
          };
          this.paginationObjs.loading = true;
          try {
            const { getApiName } = this.interfaceObj;
            const data = await getApiName({ ...obj, type: this.type });
            this.paginationObjs.loading = false;
            this.tableData = data.rows;
            this.tableData.map((item) => {
              item.promotionStartTime =
                item.promotionStartTime + ' 至 ' + item.promotionEndTime;
            });
            console.log(this.tableData);
            this.paginationObjs.total = data.total;
          } catch (error) {
            this.paginationObjs.loading = false;
          }
        },
        // 获取分类
        getGroup: async () => {
          const { groupApiName } = this.interfaceObj;
          const { code, rows } = await groupApiName({ type: this.type });
          if (code === 0) {
            const goodsTypeId = this.inputList.find(
              (item) => item.name === 'goodsTypeId'
            );
            goodsTypeId.optionList = rows.map((item, index) => {
              return {
                name: item.typeName,
                value: item.id,
              };
            });
          }

          return rows;
        },
        handleDelete: async (id) => {
          const { delApiName } = this.interfaceObj;
          const { code } = await delApiName({ id });
          if (code === 0) {
            this.$modal.msgSuccess('删除成功');
          }
          this.network().getList();
        },
      };
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-message-box__title span {
  position: relative;
  left: 37px !important;
}
</style>
